package cn.gzten.lambda.dynamo.util;

import cn.gzten.lambda.runtime.exception.AppServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

public class AppTableMapper {
    private static final ObjectMapper OBJECT_MAPPER = com.fasterxml.jackson.databind.json.JsonMapper.builder()
            .configure(MapperFeature.USE_ANNOTATIONS, false)
            .build();
    public static <T> Optional<T> itemToBean(Map<String, AttributeValue> item, Class<T> clazz) {

        if (item == null) {
            return Optional.empty();
        }
        try {
            return Optional.of(OBJECT_MAPPER.treeToValue(JsonAttributeValueUtil.fromAttributeValue(item), clazz));
        } catch (JsonProcessingException e) {
            throw new AppServiceException(e);
        }
    }

    public static final Map<String, AttributeValue> singleMapWithString(final String key, final String value) {
        return Collections.singletonMap(key, AttributeValue.builder().s(value).build());
    }
}
